#include "OpenCLGL_Util.h"

void previewPixelBuffer(int bWidth,int bHeight, GLuint buffer)
{
	float * ptr;
	glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, buffer);
	ptr = (float*)glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_WRITE);
	cv::Mat viewer =  cv::Mat::zeros(bWidth,bHeight,CV_8UC1);

	for (int i =0; i<bHeight; i++){
		for (int j=0; j<bWidth ;j++){
			viewer.at<uchar>(i,j) = (uchar)ptr[(bHeight-1-i)*bWidth+j]*255;
		}
	}
	glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0);
	cv::imshow("pixelBuffer preview",viewer);
	cv::waitKey();
}

void previewTexture2D(int tWidth,int tHeight, GLuint & texture)
{
	std::vector<float> inputDepth;
	inputDepth.resize(tWidth*tHeight);

	glBindTexture( GL_TEXTURE_2D , texture );
	glGetTexImage(GL_TEXTURE_2D ,0 ,GL_RED ,GL_FLOAT ,inputDepth.data());
	glBindTexture( GL_TEXTURE_2D , 0 );

	cv::Mat viewer =  cv::Mat::ones(tHeight,tWidth,CV_32F);
	for (int i =0; i<tHeight; i++){
		for (int j=0; j<tWidth ;j++){
			size_t pxIndex = (tHeight-1-i)*tWidth+j;
			if (inputDepth[pxIndex]!= 0)
			{
				viewer.at<float>(i,j) = inputDepth[pxIndex];
			}
		}
	}
	cv::imshow("texture2d Preview",viewer);
	cv::waitKey();
}

int showDataCLMem1D(int bWidth,int bHeight,cl_mem buf,cl_command_queue & commandQueue)
{
	int arraySize = bWidth*bHeight;
	float * outData = new float[arraySize];
	int status = clEnqueueReadBuffer(commandQueue, buf, CL_TRUE, 0, 
		arraySize*sizeof(float), 
		outData, 
		0, NULL,NULL);

	status = clFlush(commandQueue);

	cv::Mat viewer =  cv::Mat::ones(bWidth,bHeight,CV_32F);
	for (int i =0; i<bHeight; i++){
		for (int j=0; j<bWidth ;j++){
			viewer.at<float>(i,j) = outData[(bHeight-1-i)*bWidth+j];
		}
	}
	cv::imshow("pixelBuffer preview",viewer);
	cv::waitKey();
	return status;
}

void copyTex2d(int bWidth,int bHeight,GLuint & sourceTex2d,GLuint& tTex2d)
{
	std::vector<float> inputDepth;
	inputDepth.resize(bWidth*bHeight);

	glBindTexture( GL_TEXTURE_2D , sourceTex2d );
	glGetTexImage(GL_TEXTURE_2D ,0 ,GL_RED ,GL_FLOAT ,inputDepth.data());
	glBindTexture( GL_TEXTURE_2D , 0 );

	glBindTexture( GL_TEXTURE_2D , tTex2d );
	glTexImage2D(GL_TEXTURE_2D ,0 ,GL_R32F ,bWidth ,bHeight ,0 ,GL_RED ,GL_FLOAT ,inputDepth.data());
	glTexParameteri( GL_TEXTURE_2D , GL_TEXTURE_MAG_FILTER , GL_LINEAR        );
	glTexParameteri( GL_TEXTURE_2D , GL_TEXTURE_MIN_FILTER , GL_LINEAR        );
	glTexParameteri( GL_TEXTURE_2D , GL_TEXTURE_WRAP_S     , GL_CLAMP_TO_EDGE );
	glTexParameteri( GL_TEXTURE_2D , GL_TEXTURE_WRAP_T     , GL_CLAMP_TO_EDGE );
	glBindTexture( GL_TEXTURE_2D , 0 );
}